package org.icec.web.core.config;

import java.sql.SQLException;

import javax.sql.DataSource;
import org.beetl.sql.core.ClasspathLoader;
import org.beetl.sql.core.Interceptor;
import org.beetl.sql.core.UnderlinedNameConversion;
import org.beetl.sql.core.db.DBStyle;
import org.beetl.sql.ext.DebugInterceptor;
import org.beetl.sql.ext.spring4.BeetlSqlDataSource;
import org.beetl.sql.ext.spring4.BeetlSqlScannerConfigurer;
import org.beetl.sql.ext.spring4.SqlManagerFactoryBean;
import org.icec.web.core.support.beetlsql.BSQLUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.alibaba.druid.util.JdbcUtils;

@Configuration
public class SystemConfig {
	/*可省略此配置*/
	@Bean("datasource")
	//@ConfigurationProperties("spring.datasource.druid")
	public DataSource dataSource() {
		return DruidDataSourceBuilder.create().build();
	}
	@Bean(name = "beetlSqlScannerConfigurer")
	public BeetlSqlScannerConfigurer getBeetlSqlScannerConfigurer() {
		BeetlSqlScannerConfigurer conf = new BeetlSqlScannerConfigurer();
		conf.setBasePackage("org.icec.web.core.sys.dao;${beetlsql.daoPackage}");
		conf.setDaoSuffix("Dao");
		conf.setSqlManagerFactoryBeanName("sqlManagerFactoryBean");
		return conf;
	}

	@Bean(name = "sqlManagerFactoryBean")
	@Autowired
	public SqlManagerFactoryBean getSqlManagerFactoryBean( DataSource datasource,DataSourceProperties basicProperties)throws SQLException {
		SqlManagerFactoryBean factory = new SqlManagerFactoryBean();
		BeetlSqlDataSource source = new BeetlSqlDataSource();
		source.setMasterSource(datasource);
		factory.setCs(source);
		factory.setInterceptors(new Interceptor[] { new DebugInterceptor() });
		factory.setNc(new UnderlinedNameConversion());
		//根据数据库驱动设置dbstyle
		String dbType=  JdbcUtils.getDbType(basicProperties.getUrl(), null);
		DBStyle dbStyle= BSQLUtils.getDBStyleFromDriveName(dbType);
		factory.setDbStyle(dbStyle);
		factory.setSqlLoader(new ClasspathLoader("/sql",dbStyle));
		return factory;
	}
	

}
